#!/bin/sh
#
# vnc -- open the docker lab's novnc frontend via a browser
#

TOP_DIR=$(cd $(dirname $0)/../../ && pwd)
. $TOP_DIR/tools/docker/config $* >/dev/null

do_unlock

get_var WEB_BROWSER chromium-browser
get_var HOST localhost
get_var VNC_PWD ubuntu
get_var VNC_PWD_VIEWONLY ubuntu
get_var CONTAINER_NAME
get_var VNC_IP $(docker inspect --format '{{ .NetworkSettings.IPAddress }}' $CONTAINER_NAME)
get_var VNC_TOKEN $(echo -n $VNC_IP | $ENCRYPT_CMD | cut -d' ' -f1 | cut -c1-$TOKEN_LENGTH)

do_lock

which $WEB_BROWSER >/dev/null 2>&1
if [ $? -eq 1 ]; then
    echo "LOG: No $WEB_BROWSER found, use firefox instead."
    WEB_BROWSER=firefox
fi

[ -z "$VNC_AUTOCONNECT" ] && VNC_AUTOCONNECT=1

# Get vnc page
#CONTAINER_WEB_URL="$WEB_HTTP://localhost:${HOST_VNC_PORT}/?u=$VNC_TOKEN&p=$VNC_PWD&autoconnect=$VNC_AUTOCONNECT&encrypt=$WEB_ENCRYPT"
#HOST_WEB_URL="$WEB_HTTP://${HOST}:${HOST_VNC_PORT}/?u=$VNC_TOKEN&p=$VNC_PWD&autoconnect=$VNC_AUTOCONNECT&encrypt=$WEB_ENCRYPT"
CONTAINER_WEB_URL="$WEB_HTTP://localhost:${HOST_VNC_PORT}/?u=$VNC_TOKEN&p=$VNC_PWD"
HOST_WEB_URL="$WEB_HTTP://${HOST}:${HOST_VNC_PORT}/?u=$VNC_TOKEN&p=$VNC_PWD"
HOST_WEB_URL_VIEWONLY="$WEB_HTTP://${HOST}:${HOST_VNC_PORT}/?r=${VNC_TOKEN}${VNC_PWD_VIEWONLY}"

[ $VNC_AUTOCONNECT -eq 1 ] && \
  CONTAINER_WEB_URL="$CONTAINER_WEB_URL&autoconnect=1"

# Create local shotcut on Desktop
if [ -d ~/Desktop -a -n "$REMOTE_DESKTOP_SHORTCUT" -a -f "$REMOTE_DESKTOP_SHORTCUT" ]; then
    echo '#!/usr/bin/env xdg-open' > $LOCAL_DESKTOP_SHORTCUT
    if [ "x$WEB_BROWSER" = "xchromium-browser" ]; then
        icon=chromium-browser.png
    else
        icon=firefox.png
    fi

    TMP_URL=`echo $CONTAINER_WEB_URL | tr '&' '|'`
    cat $REMOTE_DESKTOP_SHORTCUT \
        | sed "s%Exec=.*%Exec=$WEB_BROWSER $TMP_URL%g" \
        | sed "s%terminator.png%$icon%g;s%lxterminal.xpm%$icon%g" | tr '|' '&' \
	  >> $LOCAL_DESKTOP_SHORTCUT
    chmod a+x $LOCAL_DESKTOP_SHORTCUT
fi

# For web portmapping
[ -f $LAB_PORTMAP ] && grep -q ":8" $LAB_PORTMAP \
    && (docker logs $CONTAINER_ID 2>/dev/null | grep "Server address:") \
    && for port in $(grep ":8" $LAB_PORTMAP | cut -d':' -f1); \
       do echo "LOG: Local Web Address: http://$HOST:$port/"; done

which $WEB_BROWSER >/dev/null 2>&1 \
    && ($WEB_BROWSER $CONTAINER_WEB_URL >/dev/null 2>&1 &)>/dev/null 2>&1

echo "Please login:"
echo
echo "  *   Normal: $HOST_WEB_URL"
echo "  * Viewonly: $HOST_WEB_URL_VIEWONLY"
echo
echo "        User: $VNC_TOKEN"
echo "    Password: $VNC_PWD"
echo "    Password: $VNC_PWD_VIEWONLY (Viewonly)"
echo
